/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.project.carshop07.db;

import edu.chl.project.carshop07.constants.JpaConstants;
import edu.chl.project.carshop07.core.Car;
import edu.chl.project.carshop07.core.Customer;
import edu.chl.project.carshop07.core.Customer_;
import edu.chl.project.carshop07.ctrl.jpa.JpaCtrl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author AMADIN
 */
public class Database {
    
    private static JpaCtrl jpa = new JpaCtrl(JpaConstants.UNIT_NAME);
    
    public static Customer getCustomer(String login, String passwd){
        EntityManager em = jpa.getEntityManager();
        try{
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Customer> rt = cq.from(Customer.class);
            Path<String> login_ = rt.get(Customer_.login);
            Path<String> passwd_ = rt.get(Customer_.passwd);
            Predicate loginCond = em.getCriteriaBuilder().equal(login_, login);
            Predicate passwdCond = em.getCriteriaBuilder().equal(passwd_,passwd);
            cq.where(em.getCriteriaBuilder().and(loginCond, passwdCond));
            TypedQuery<Customer> tq = em.createQuery(cq);
            return tq.getSingleResult();

        }catch (NoResultException nre){
            return null;   
        }finally {
            em.close();
        }
    }
    
    public static void addCustomer(Customer c){
        jpa.create(c);
    }

    public static List<Car> getProducts() {
        return jpa.findEntities(Car.class); 
    }
    public static Car getProduct(Long id) {
        return jpa.findEntity(id, Car.class); 
    }
}
